import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tooltip, Menu, Row, Col, Avatar, Input, Spin, Popconfirm, message } from 'antd';
import { ContentPackage, ModalC, IconC, FormItemLayout } from '../../comps';

import styles from './index.less';
import AttentionTable from './AttentionTable';
import DelPng from '../../assets/busi/MyAttention/delete_blue.png';
import EditPng from '../../assets/busi/MyAttention/edit_blue.png';

const { SubMenu } = Menu;
const FormItem = Form.Item;
@Form.create()
class MyAttention extends PureComponent {
  state = {
    openBondGroup: true, // 个券组展开
    openMainGroup: true, // 主体组展开
    visibleModal: false, // 新增个券组/主体组弹出框
    visibleEditModal: false, // 编辑个券组/主体组弹出框
    isBond: false, // 是否为新增个券组弹窗
    bondGroupList: [],
    mainGroupList: [],
    bondLoading: true,
    mainLoading: true,
    selectedKeys: [], // 初始选中的菜单项 key 数组
    noTableData: false, // table页面无数据
    selectId: '', // 选择查看组的id
    selectName: '', // 选择查看组的名称
    selectType: '', // 选择查看个券/主体组
    editId: '', // 编辑组的id
    editName: '', // 编辑组的名称
    isDefault: undefined, // 是否是券池过来的个券组数据
  };

  componentDidMount() {
    this.getData();
  }

  // 找出相同名称的数据
  findSame = (arr) => {
    const obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (obj[arr[i].title]) {
        const item = obj[arr[i].title];
        if (item.isDefault === '0') item.title = `${item.title}【自定义】`; // 名称修改加上自定义 利用对象的指向
      } else {
        obj[arr[i].title] = arr[i]; // 将每个元素 作为obj对象的key，通过判断key是否存在来判断重复的元素
      }
    }
    return arr;
  };

  // 获取组列表
  getData = () => {
    const { dispatch } = this.props;
    // 获取个券组列表
    dispatch({
      type: 'myAttentionM/getBondGroupList',
      payload: {},
      callback: (res) => {
        const data = this.findSame(res.data || []);
        this.setState({
          bondGroupList: data,
          bondLoading: false,
        });
      },
    });

    // 获取主体组列表
    dispatch({
      type: 'myAttentionM/getMainGroupList',
      payload: {},
      callback: (res) => {
        this.setState({
          mainGroupList: res.data,
          mainLoading: false,
        });
      },
    });
  };

  // 设置菜单默认选中项
  setDefault = () => {
    const { bondGroupList, mainGroupList, selectedKeys, selectId } = this.state;
    if (!selectId) {
      if (bondGroupList.length > 0 || mainGroupList.length > 0) {
        let keyItem, keyname, subkey, isDefault;
        if (bondGroupList.length > 0) {
          subkey = 'bond';
          keyItem = bondGroupList[0].value;
          keyname = bondGroupList[0].title;
          isDefault = bondGroupList[0].isDefault; // 是否是券池来的默认数据
        } else if (mainGroupList.length > 0) {
          subkey = 'main';
          keyItem = mainGroupList[0].value;
          keyname = mainGroupList[0].title;
          isDefault = '0'; // 是否是券池来的默认数据 否
        }
        selectedKeys.push(keyItem);
        this.setState({
          noTableData: false,
          selectedKeys,
          selectId: keyItem,
          selectName: keyname,
          selectType: subkey,
          isDefault,
        });
      } else {
        this.setState({
          noTableData: true,
        });
      }
    }
  };

  // SubMenu 展开/关闭的回调---获取已展开列表
  subMenuClick = (openKeys) => {
    this.setState({
      openBondGroup: openKeys.includes('bond'),
      openMainGroup: openKeys.includes('main'),
    });
  };

  // 导航选择事件
  selectClick = (value) => {
    const { bondGroupList, mainGroupList } = this.state;
    const newList1 = bondGroupList.filter((item) => {
      return item.value == value.key;
    });
    const newList2 = mainGroupList.filter((item) => {
      return item.value == value.key;
    });
    if (newList1.length) {
      this.setState({
        selectId: newList1[0].value,
        selectName: newList1[0].title,
        selectType: 'bond',
        noTableData: false,
        isDefault: newList1[0].isDefault, // 是否是券池来的默认数据
      });
    } else if (newList2.length) {
      this.setState({
        selectId: newList2[0].value,
        selectName: newList2[0].title,
        selectType: 'main',
        noTableData: false,
        isDefault: '0', // 是否是券池来的默认数据 否
      });
    }
  };

  // 新增个券/主体组btn
  addGroupBtn = (e, type) => {
    e.stopPropagation();
    this.setState({
      visibleModal: true,
      isBond: type == 'bond',
    });
  };

  // 新增个券/主体组弹窗
  showAddModel = () => {
    const {
      form: { getFieldDecorator, validateFields, resetFields },
      dispatch,
      currentUser,
    } = this.props;
    const { visibleModal, isBond, bondGroupList, mainGroupList } = this.state;
    const modalProps = {
      visible: visibleModal,
      onOk: () => {
        validateFields((err, values) => {
          if (!err) {
            const type = isBond ? 1 : 2;
            dispatch({
              type: 'myAttentionM/addGroup',
              payload: {
                name: values.name,
                type,
              },
              callback: (res) => {
                message.success('添加成功');
                resetFields();
                this.setState({
                  visibleModal: false,
                  bondLoading: true,
                });
                this.getData();
              },
            });
          }
        });
      },
      onCancel: () => {
        resetFields();
        this.setState({
          visibleModal: false,
        });
      },
      title: isBond ? '新增个券组' : '新增主体组',
      className: 'addModal',
      width: 380,
      maskClosable: false, // 点击蒙层是否允许关闭
    };
    return (
      <ModalC {...modalProps}>
        <Form>
          <Row>
            <Col md={24} sm={24}>
              <FormItem {...FormItemLayout} label={isBond ? '个券组' : '主体组'}>
                {getFieldDecorator('name', {
                  initialValue: `自定义${isBond ? '个券组' : '主体组'}${isBond ? bondGroupList.length + 1 : mainGroupList.length + 1}`,
                  rules: [{ required: true, message: '名称不能为空!' }],
                })(<Input maxLength={20} />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </ModalC>
    );
  };

  // 编辑个券/主体组btn  type: 'bond'-个券组  'main'-主体组
  editGroupBtn = (e, obj, type) => {
    e.stopPropagation();
    this.setState({
      visibleEditModal: true,
      isBond: type == 'bond',
      editId: obj.value,
      editName: obj.title,
    });
  };

  // 编辑个券/主体组弹窗
  showEditModel = () => {
    const {
      form: { getFieldDecorator, validateFields, resetFields },
      dispatch,
      currentUser,
    } = this.props;
    const { visibleEditModal, isBond, editName, editId, selectId } = this.state;
    const modalProps = {
      visible: visibleEditModal,
      onOk: () => {
        validateFields((err, values) => {
          if (!err) {
            const type = isBond ? 1 : 2;
            dispatch({
              type: 'myAttentionM/editGroup',
              payload: {
                name: values.groupName,
                type,
                groupId: editId,
              },
              callback: (res) => {
                message.success('编辑成功');
                resetFields();
                if (editId == selectId) {
                  this.setState({
                    selectName: values.groupName,
                  });
                }
                this.setState({
                  visibleEditModal: false,
                  bondLoading: true,
                });
                this.getData();
              },
            });
          }
        });
      },
      onCancel: () => {
        resetFields();
        this.setState({
          visibleEditModal: false,
        });
      },
      title: isBond ? '编辑个券组' : '编辑主体组',
      className: 'addModal',
      width: 380,
      maskClosable: false, // 点击蒙层是否允许关闭
    };
    return (
      <ModalC {...modalProps}>
        <Form>
          <Row>
            <FormItem {...FormItemLayout} label={isBond ? '个券组' : '主体组'}>
              {getFieldDecorator('groupName', {
                initialValue: editName,
                rules: [{ required: true, message: '名称不能为空!' }],
              })(<Input maxLength={20} />)}
            </FormItem>
          </Row>
        </Form>
      </ModalC>
    );
  };

  // 删除个券/主体组btn
  onDeleteGroupBtn = (e, obj, type) => {
    e.stopPropagation();
    this.setState({
      isBond: type == 'bond',
    });
  };

  // 删除个券/主体组
  onDeleteGroup = (obj) => {
    const { dispatch } = this.props;
    const type = this.state.isBond ? 1 : 2;
    dispatch({
      type: 'myAttentionM/deleteGroup',
      payload: {
        type,
        groupId: obj.value,
      },
      callback: (res) => {
        message.success('删除成功');
        this.setState({
          bondLoading: true,
        });
        if (obj.value == this.state.selectId) {
          // 删除后判断组是否还存在---显示无状态
          this.setState({
            noTableData: true,
          });
        }
        this.getData();
      },
    });
  };

  // 左侧导航栏
  navLeft = () => {
    const { bondLoading, mainLoading, openBondGroup, openMainGroup, selectedKeys, bondGroupList, mainGroupList } = this.state;
    this.setDefault();
    return (
      <Spin spinning={bondLoading || mainLoading}>
        <div className={`${styles.menuBox} ${openBondGroup && openMainGroup ? styles.selectBox : ''}`}>
          <Menu mode='inline' onOpenChange={this.subMenuClick} onSelect={this.selectClick} defaultOpenKeys={['bond', 'main']} defaultSelectedKeys={selectedKeys}>
            <SubMenu
              key='bond'
              title={
                <div className='menu-title' style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span className={openBondGroup ? 'title-right-select' : 'title-right'}>个券组</span>
                  <div
                    className='menu-title-left'
                    onClick={(e) => {
                      this.addGroupBtn(e, 'bond');
                    }}
                  >
                    <IconC type={'plus'} />
                    <span style={{ paddingRight: '8px' }}>新增个券组</span>
                  </div>
                </div>
              }
            >
              {bondGroupList.length
                ? bondGroupList.map((item) => (
                    <Menu.Item key={item.value}>
                      <div className='menu-list'>
                        <Tooltip title={item.title} mouseEnterDelay={1}>
                          <span>{item.title}</span>
                        </Tooltip>
                        {item.isDefault === '0' && (
                          <div className='menu-item'>
                            <div
                              onClick={(e) => {
                                e.stopPropagation();
                                this.editGroupBtn(e, item, 'bond');
                              }}
                            >
                              <img alt='编辑' src={EditPng} className='icon' />
                            </div>
                            <div>
                            <Popconfirm
                              key={item.value}
                              title='确定删除？'
                              icon={<QuestionCircleOutlined />}
                              onConfirm={(e) => {
                                this.onDeleteGroup(item);
                                }}
                            >
                                <div onClick={(e) => this.onDeleteGroupBtn(e, item, 'bond')}>
                                  <img alt='删除' src={DelPng} className='icon' />
                                </div>
                              </Popconfirm>
                            </div>
                          </div>
                        )}
                      </div>
                    </Menu.Item>
                  ))
                : null}
            </SubMenu>

            <SubMenu
              key='main'
              title={
                <div className='menu-title' style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span className={openMainGroup ? 'title-right-select' : 'title-right'}>主体组</span>
                  <div
                    className='menu-title-left'
                    onClick={(e) => {
                      this.addGroupBtn(e, 'main');
                    }}
                  >
                    <IconC type={'plus'} />
                    <span style={{ paddingRight: '8px' }}>新增主体组</span>
                  </div>
                </div>
              }
            >
              {mainGroupList.length
                ? mainGroupList.map((item) => (
                    <Menu.Item key={item.value}>
                      <div className='menu-list'>
                        <Tooltip title={item.title} mouseEnterDelay={1}>
                          <span>{item.title}</span>
                        </Tooltip>
                        <div className='menu-item'>
                          <div onClick={(e) => this.editGroupBtn(e, item, 'main')}>
                            <img alt='编辑' src={EditPng} className='icon' />
                          </div>
                          <Popconfirm
                            key={item.value}
                            title='确定删除？'
                            icon={<QuestionCircleOutlined />}
                            onConfirm={(e) => {
                              this.onDeleteGroup(item);
                            }}
                          >
                            <div onClick={(e) => this.onDeleteGroupBtn(e, item, 'main')}>
                              <img alt='删除' src={DelPng} className='icon' />
                            </div>
                          </Popconfirm>
                        </div>
                      </div>
                    </Menu.Item>
                  ))
                : null}
            </SubMenu>
          </Menu>
        </div>
        {!this.state.visibleEditModal ? this.showAddModel() : this.showEditModel()}
      </Spin>
    );
  };

  render() {
    const { selectId, selectName, selectType, noTableData } = this.state;
    return (
      <ContentPackage
        title='我的关注'
        contentHtml={
          <div className={styles.attentionBox}>
            <Row>
              <Col span='6'>{this.navLeft()}</Col>
              <Col span='18'>
                <AttentionTable selectId={selectId} selectName={selectName} isDefault={this.state.isDefault} selectType={selectType} noTableData={noTableData} />
              </Col>
            </Row>
          </div>
        }
      />
    );
  }
}

export default connect(({ myAttentionM, userM: user }) => ({ myAttentionM, currentUser: user.currentUser }))(MyAttention);
